<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkDepartment\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\App\WorkDepartment\Event\DeleteDepartmentRawEvent;

/**
 * 部门删除事件.
 *
 * @Listener
 */
class DeleteDepartmentRawListener implements ListenerInterface
{
    /**
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @var array
     */
    private $message;

    public function listen(): array
    {
        return [
            DeleteDepartmentRawEvent::class,
        ];
    }

    /**
     * @return string
     */
    public function process(object $event)
    {
        try {
            $this->message = $event->message;
            $this->logger = make(StdoutLoggerInterface::class);
            if (empty($this->message)) {
                $this->logger->error('DepartmentMoveHandler->process同步删除部门message不能为空');
                return 'success';
            }
            // 获取公司corpId
            $this->corpService = make(CorpContract::class);
            $corpIds = $this->getCorpId();
            if (empty($corpIds)) {
                $this->logger->error('DepartmentMoveHandler->process同步删除部门corpIds不能为空');
                return 'success';
            }
            // 部门
            $this->workDepartmentService = make(WorkDepartmentContract::class);
            $departments = $this->getDepartmentData($corpIds);
            if (empty($departments)) {
                $this->logger->info('DepartmentMoveHandler->process同步删除部门部门为空');
                return 'success';
            }
            // 删除部门
            if (! empty($departments[$this->message['Id']])) {
                $result = $this->workDepartmentService->deleteWorkDepartment($departments[$this->message['Id']]);
                if (empty($result)) {
                    $this->logger->error('DepartmentMoveHandler->process微信删除部门失败');
                }
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('企业部门信息删除回调失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }

        return 'success';
    }

    /**
     * 获取公司corpId.
     */
    private function getCorpId(): array
    {
        $corpData = $this->corpService->getCorpsByWxCorpId($this->message['ToUserName'], ['id']);
        if (empty($corpData)) {
            return [];
        }
        return [$corpData['id']];
    }

    /**
     *  部门基础信息.
     * @param $corpIds
     */
    private function getDepartmentData($corpIds): array
    {
        $department = [];
        $departmentData = $this->workDepartmentService->getWorkDepartmentsByCorpIds($corpIds, ['id', 'wx_department_id']);
        if (empty($departmentData)) {
            return [];
        }
        foreach ($departmentData as $dk => $dv) {
            $department[$dv['wxDepartmentId']] = $dv['id'];
        }
        return $department;
    }
}
